package com.cy.module.dingtalk.mobility;

import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Account;
import com.cy.model.ProductOfOutput;
import com.cy.model.ProductOutput;
import com.cy.utils.dingtalk.DingTalkUtils;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@ControllerBind(controllerKey = "/clmp/dingtalk/mobility/productOutput")
public class ProductOutputController extends com.cy.module.ProductOutputController {

    @Override
    public void index() {
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Map<String, String[]> paraMap = getParaMap();
        ProductOutput productOutput = new ProductOutput();
        for (Map.Entry<String, String[]> param : paraMap.entrySet()){
            String key = param.getKey();
            if ("pageIndex".equals(key) || "limit".equals(key) || "totalPage".equals(key))
                continue;
            if (StringUtils.isNotBlank(param.getValue()[0]))
                productOutput.put(param.getKey(), param.getValue()[0]);
        }
        Page<ProductOutput> pageModel = ProductOutput.dao.paginate(page, pageSize, "po.*, a.account AS operator_name", productOutput);
        for (ProductOutput po : pageModel.getList()){
            po.put("products", ProductOfOutput.dao.findByOutputId(po.getId()));
        }
        renderBuiPage(pageModel, 200);
    }

    public void saveOrUpdate() {
        ProductOutput model = getModel(ProductOutput.class);
        String[] sns = getParaValues("sns");
        Long id = model.getId();
        if (id == null){//新增
            Account loginAccount = getLoginAccount();
            model.setOperatorId(loginAccount.getAccountId());
            model.setOutputTime(new Date());
            try {
                model.save();
                StringBuilder msg = new StringBuilder();
                List<ProductOfOutput> products = new ArrayList<>(sns.length);
                for (String sn : sns){
                    try {
                        ProductOfOutput po = new ProductOfOutput();
                        po.setOutputId(model.getId());
                        po.setSn(sn);
                        products.add(po);
                    } catch (Exception e){
                        msg.append(sn).append("内部错误");
                    }
                }
                if(products.size() > 0){
                    String column = "sn,output_id";
                    int[] batch = Db.batch("INSERT INTO product_of_output (" + column + ") VALUES (?,?)", column, products, 50);
                    postSave(products);
                    msg.append("成功新增"+ batch.length +"条");
                }
                renderSuccess(msg.toString());
            } catch (Exception e) {
                e.printStackTrace();
                renderFail();
            }
        } else {//修改
            ProductOutput productOutput = ProductOutput.dao.findById(id);
            productOutput.cover(model);
            productOutput.update();

            List<String> snsList = Lists.newArrayList(sns);
            List<ProductOfOutput> originalRecords = ProductOfOutput.dao.findByOutputId(id);

            //排除相同元素不做修改
            for (Iterator<ProductOfOutput> originalRecordsIt = originalRecords.listIterator(); originalRecordsIt.hasNext();){
                ProductOfOutput originalRecord = originalRecordsIt.next();
                for(Iterator<String> snsIt = snsList.listIterator(); snsIt.hasNext();){
                    String sn = snsIt.next();
                    if (originalRecord.getSn().equals(sn)){
                        originalRecordsIt.remove();
                        snsIt.remove();
                        break;
                    }
                }
            }

            List<String> originalRecordIds = new ArrayList<>(originalRecords.size());
            for (ProductOfOutput poo : originalRecords)
                originalRecordIds.add(String.valueOf(poo.getId()));

            try {
                //删除原有多余的产品
                if (originalRecordIds.size() > 0)
                    ProductOfOutput.dao.deleteBatch("id", originalRecordIds.toArray());
                //新增不存在的产品
                for (String sn : snsList)
                    new ProductOfOutput().setSn(sn).setOutputId(id).save();
                postSave(snsList);
                renderSuccess();
            } catch (Exception e){
                e.printStackTrace();
                renderFail();
            }
        }
    }

    public void info(){
        String expressNum = getPara("express_num");
        ProductOutput productOutput = ProductOutput.dao.findByExpressNum(expressNum);
        if (productOutput != null){
            List<ProductOfOutput> products = ProductOfOutput.dao.findByOutputId(productOutput.getId());
            productOutput.put("operator", productOutput.getOperator());
            setAttr("products", products);
            setAttr("productOutput", productOutput);
        } else {
            ProductOutput temp = new ProductOutput();
            temp.setExpressNum(expressNum);
            temp.put("operator", getLoginAccount());
            setAttr("productOutput", temp);
        }
        setAttr("config", DingTalkUtils.getJsapiConfig(getRequest()));
        renderJsp("/view/dingtalk/mobility/ProductOutput-scan.jsp");
    }

}